import Cookie from 'js-cookie'

const tokenKey = '__site_token'

const auth = {
  get: function() {
    return Cookie.get(tokenKey)
  },
  set: function(token) {
    Cookie.set(tokenKey, token)
  },
  remove: function() {
    Cookie.remove(tokenKey)
  }
}

const _createScript = function(src, resolve, reject) {
  if (typeof src === 'string') {
    src = {
      id: '',
      src: src
    }
  }
  if (src.id && document.getElementById(src.id)) {
    resolve()
    return
  }
  let script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = src.src
  script.async = true
  script.charset = 'utf-8'
  if (src.id) {
    script.id = src.id
  }
  document.head.appendChild(script)
  resolve && (script.onload = resolve)
  reject && (script.onerror = reject)
  return script
}

/**
 * 动态加载script
 * @param {object} scripts
 */
export function loadScript(scripts) {
  return new Promise((resolve, reject) => {
    if (!(scripts instanceof Array)) {
      scripts = [scripts]
    }
    let index = 0
    let len = scripts.length
    let loaded = function() {
      index++
      if (index >= scripts.length) {
        resolve()
        console.log(`load scripts:${index}`)
        return
      }
      _createScript(scripts[index], loaded, loaded)
    }
    _createScript(scripts[index], loaded, loaded)
  })
}

const mapProp = 'BMap'
/**
 * 百度地图
 */
export function BaiduMap() {
  if (window.hasOwnProperty(mapProp)) {
    return new Promise(resolve => {
      resolve(window[mapProp])
    })
  }
  const ak = 'kibaCYTHOi9WolKpcT4xKgQt'
  // const BMap = {}
  return new Promise(function(resolve, reject) {
    window.bMapInit = function() {
      resolve(window[mapProp])
    }
    let src = `http://api.map.baidu.com/api?v=2.0&ak=${ak}&callback=bMapInit`
    _createScript(src, false, reject)
  })
}

const singerProp = 'SINGER'
/**
 * SINGER
 */
export function Singer() {
  if (window.hasOwnProperty(singerProp)) {
    return new Promise(resolve => {
      resolve(window[singerProp])
    })
  }
  return new Promise(resolve => {
    _createScript('http://static.dayeasy.net/v3/js/singer.min.js', () => {
      resolve(window[singerProp])
    })
  })
}

export function fileReader(file) {
  return new Promise((resolve, reject) => {
    if (typeof FileReader === 'undefined') {
      reject(new Error('您的浏览器不支持图片上传，请升级您的浏览器'))
      return false
    }
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function(e) {
      resolve(e.target.result)
    }
  })
}
export { auth }
